import React, { Component } from 'react';
import PropTypes from 'prop-types';
import styles from '../barChart/index.less';
import { Empty } from 'antd';
import echarts from 'echarts/lib/echarts';
import 'echarts/lib/chart/bar'; //柱状图
// 引入提示框和标题组件
import 'echarts/lib/component/tooltip'; //提示框
import 'echarts/lib/component/title'; //标题
import 'echarts/lib/component/legend'; //图例
import 'echarts/lib/component/legendScroll'; //图例

/**
 * 柱状图
 * @param props
 * @returns {*}
 * @constructor
 */
class RcBarCharts extends Component {
  constructor(props) {
    super(props);
    this.state = {
      myEchart: null,
      noData: false, //是否无数据
      mapOpacity: 0,
      yNewAxis: {
        type: 'value',
        nameTextStyle: {
          color: '#9497AA',
          fontSize: this.props.yAxis.fontSize || null, //Y轴单位的字体大小
          padding: this.props.yAxis.padding || null, //Y轴单位的字体大小
        },
        axisLabel: {
          show: true,
          inside: this.props.yAxis.inside || false, //Y轴的数是否朝内显示
          verticalAlign: this.props.yAxis.inside || false ? 'bottom' : 'center',
          textStyle: {
            color: '#9497AA',
          },
        },
        splitLine: {
          show: this.props.lineShow1,
          lineStyle: {
            color: '#202b59',
          },
        },
        axisLine: {
          show: this.props.lineShow,
          lineStyle: {
            color: '#e7eaed',
          },
        },
        axisTick: {
          //y轴刻度线
          show: this.props.YaxisTick,
        },
      },
      grid: {
        top: '15%',
        left: '0%',
        right: '0%',
        bottom: '0%',
        containLabel: true,
      },
      legendName: [],
    };
  }

  componentDidMount() {
    //页面加载的时候点开就可以展示，加载完成之后再点开就不能展示
    this.setState(
      {
        myEchart: echarts.init(window.document.getElementById(this.props.id)),
      },
      () => {
        window.addEventListener('resize', () => {
          this.state.myEchart.resize();
        });
        // this.state.myEchart.showLoading({text: '数据加载中'});
        this.state.myEchart.on('click', (data) => {
          this.props.click && this.props.click(data);
        });
        //解决当 echarts 节点是 有数据后再挂载节点的问题  手动触发 props更新
        if (this.props.xData.length > 0 && this.props.yData.length > 0) {
          this.componentWillReceiveProps(this.props);
        }
      },
    );
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.xData.length > 0 && nextProps.xData[0] === null) {
      return;
    }
    if (
      JSON.stringify(nextProps.yData) === JSON.stringify(this.props.yData) &&
      JSON.stringify(nextProps.xData) === JSON.stringify(this.props.xData)
    ) {
      return;
    }

    if (nextProps.xData.length > 0 && nextProps.yData.length > 0) {
      this.setState(
        {
          noData: false,
          yData: nextProps.yData,
          legendName: nextProps.legendName,
        },
        () => {
          this.state.myEchart.clear();
          this.state.myEchart.hideLoading();
          let {
            id,
            xData,
            yData,
            legendName,
            title,
            stack,
            barWidth,
            legendLength,
            yAxis,
            grid,
            color,
            legendShow,
          } = nextProps;
          this.setEcharts(
            id,
            xData,
            yData,
            legendName,
            title,
            stack,
            barWidth,
            legendLength,
            yAxis,
            grid,
            color,
            legendShow,
          );
        },
      );
    } else {
      this.setState(
        {
          noData: true,
        },
        () => {
          this.state.myEchart.clear();
          this.state.myEchart.hideLoading();
        },
      );
    }
  }

  setEcharts = (
    id,
    xData,
    yData,
    legendName,
    title,
    stack,
    barWidth,
    legendLength,
    yAxis,
    grid,
    color,
    legendShow,
  ) => {
    let seriesData = [];
    let newGrid = Object.assign(this.state.grid, grid);
    let legendSelected = {},
      yNewAxis = {};
    if (legendLength) {
      legendName.forEach((item, index) => {
        if (index + 1 > legendLength) {
          legendSelected[item] = false;
        }
      });
    }
    yNewAxis = Object.assign(yAxis, this.state.yNewAxis);
    let option = {
      title: {
        text: title,
        subtext: 'KW',
        left: 5, // 距离左边位置
        top: -17, // 距离上面位置
        subtextStyle: {
          // 设置二级标题的样式
          color: '#ccc',
          fontSize: 10,
        },
        padding: [10, 0, 0, 10],
        textStyle: {
          color: '#000',
          fontWeight: 'normal',
          fontSize: 16,
        },
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: '',
        },
        formatter: function (params, ticket, callback) {
          return (
            `${params[0].axisValue}${
              params[0].seriesName.indexOf('天') !== -1
                ? '时'
                : params[0].seriesName.indexOf('月') !== -1
                ? '日'
                : '月'
            }<br/>` +
            params
              .map((item) => `${item.seriesName}: ${item.value}`)
              .join('<br />')
          );
        },
        // formatter: `{b0}${} <br />{a0}: {c0}<br />{a1}: {c1}`
      },
      legend: {
        show: legendShow,
        width: '70%',
        type: 'scroll',
        data: legendName,
        x: 'right',
        padding: [10, 20, 0, 0],
        selected: legendSelected,
        icon: 'square',
        itemWidth: 10,
        itemHeight: 10,
        textStyle: { color: 'white', size: 10 },
      },
      grid: newGrid,
      xAxis: [
        {
          type: 'category',
          data: xData,
          axisLabel: {
            //坐标轴刻度标签的相关设置。
            show: true,
            textStyle: {
              color: '#9497AA',
            },
            rotate: this.props.rotate,
          },
          axisTick: {
            show: false,
          },
          axisLine: {
            show: false,
            lineStyle: {
              color: '#e7eaed',
            },
          },
        },
      ],
      yAxis: yNewAxis,
      series: [
        {
          name: this.state.legendName[0],
          type: 'bar',
          stack: stack,
          data: this.state.yData[0],
          barWidth: barWidth, //柱图宽度
          animation: true, // 是否开启动画
          barGap: '0%',
          itemStyle: {
            // 图形的形状
            color: '',
            barBorderRadius: [3, 3, 0, 0],
            normal: {
              color: new echarts.graphic.LinearGradient(
                1,
                0,
                1,
                1,
                [
                  //设置颜色 渐变色
                  { offset: 0, color: '#20FFE9' },
                  { offset: 1, color: '#1890FF' },
                ],
                false,
              ),
              label: {
                formatter: '',
                show: true,
                // padding:[0,0,0,17],
                // position:"top",
                textStyle: {
                  fontSize: '12',
                  color: '#DE4C5A',
                },
              },
              barBorderRadius: [15, 15, 0, 0],
            },
          },
        },
        {
          name: this.state.legendName[1],
          type: 'line',
          stack: stack,
          data: this.state.yData[1],
          barWidth: barWidth, //柱图宽度
          animation: true, // 是否开启动画
          barGap: '0%',
          itemStyle: {
            // 图形的形状
            color: '',
            barBorderRadius: [3, 3, 0, 0],
            normal: {
              color: new echarts.graphic.LinearGradient(
                1,
                0,
                1,
                1,
                [
                  //设置颜色 渐变色
                  { offset: 0, color: '#FAD961' },
                  { offset: 1, color: '#F76B1C' },
                ],
                false,
              ),
              label: {
                formatter: '',
                show: true,
                // padding:[0,0,0,17],
                // position:"top",
                textStyle: {
                  fontSize: '12',
                  color: '#DE4C5A',
                },
              },
              barBorderRadius: [15, 15, 0, 0],
            },
          },
        },
      ],
    };
    if (color && color.length == legendName.length) {
      option.color = color;
    }

    this.state.myEchart.setOption(option);
    this.state.myEchart.hideLoading();
    this.setState({
      mapOpacity: 1,
    });
  };

  render() {
    return (
      <div className={styles.rcpiechart}>
        <div id={this.props.id} style={{ width: '100%', height: '100%' }}></div>
        {this.state.noData && (
          <div className={styles.rcempty}>
            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE}></Empty>
          </div>
        )}
      </div>
    );
  }
}

/*需要的参数*/
RcBarCharts.propTypes = {
  stack: PropTypes.bool, //每一条数据是否是叠加在一起的
  barWidth: PropTypes.number, //柱图每一条柱子的宽度
  legendLength: PropTypes.number, //图例显示的个数
  id: PropTypes.string.isRequired, //id
  xData: PropTypes.array.isRequired, //x轴刻度值
  yData: PropTypes.array.isRequired, //数据
  legendName: PropTypes.array, //图例名称
  legendShow: PropTypes.bool, //图例是否显示
  title: PropTypes.string, //标题
  yAxis: PropTypes.object, // Y轴的设置
  grid: PropTypes.object,
  click: PropTypes.func, //点击事件
  color: PropTypes.array, //颜色
  YaxisTick: PropTypes.bool, //y轴刻度线是否展示
  lineShow: PropTypes.bool, //是否展示网格线
  rotate: PropTypes.number,
};

/*参数的默认值*/
RcBarCharts.defaultProps = {
  legendShow: true,
  id: 'bar',
  title: '',
  legendName: [],
  stack: false, //每一条数据是否是叠加在一起的
  barWidth: 20, //柱图每一条柱子的宽度
  yAxis: {},
  grid: {},
  YaxisTick: true,
  lineShow: true,
  lineShow1: true,
  rotate: 0,
};

export default RcBarCharts;
